package com.qs.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.qs.exception.ServiceException;
import com.qs.mapper.CommentMapper;
import com.qs.mapper.UserGoodsLogMapper;
import com.qs.mapper.UserMapper;
import com.qs.model.dto.CommentDto;
import com.qs.model.entity.Comment;
import com.qs.model.entity.User;
import com.qs.model.entity.UserGoodsLog;
import com.qs.model.enums.CommentEnum;
import com.qs.model.vo.CommentVo;
import com.qs.response.ResponseEnum;
import com.qs.service.ICommentService;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author author
 * @since 2024-03-24
 */
@Service
@RequiredArgsConstructor
public class CommentServiceImpl extends ServiceImpl<CommentMapper, Comment> implements ICommentService {

    private final UserMapper userMapper;
    private final UserGoodsLogMapper userGoodsLogMapper;

    @Override
    public List<CommentDto> findGoodsComment(Integer id) {
        if(null == id){
            throw new ServiceException(ResponseEnum.BAD_REQUEST);
        }
        QueryWrapper<Comment> wrapper = new QueryWrapper<>();
        wrapper.eq("goods_id", id);
        List<Comment> comments = baseMapper.selectList(wrapper);
        if(!CollectionUtils.isEmpty(comments)){
            List<CommentDto> list = new ArrayList<>();
            comments.stream().forEach(comment ->{
                User user = userMapper.selectById(comment.getUserId());

                CommentDto commentDto = new CommentDto();
                commentDto.setAvatar(user.getAvatar());
                commentDto.setId(comment.getId());
                commentDto.setComment(comment.getComment());
                commentDto.setScore(comment.getScore());
                commentDto.setUsername(user.getNickName());
                commentDto.setCreateTime(comment.getCreateTime());

                list.add(commentDto);
            });
            return list;
        }
        return null;
    }

    @Override
    public void saveGoodsComment(CommentVo commentVo) {
        UserGoodsLog userGoodsLog = userGoodsLogMapper
                .selectOne(new QueryWrapper<UserGoodsLog>()
                        .eq("order_id", commentVo.getOrderId()));
        //将支付日志的一条记录做修改
        if(null != userGoodsLog){
            userGoodsLog.setIsComment(CommentEnum.HAVE_COMMENT);
            userGoodsLogMapper.updateById(userGoodsLog);
        }
        Comment comment = new Comment();
        BeanUtils.copyProperties(commentVo, comment);
        baseMapper.insert(comment);
    }
}
